package com.gserver.game.plugin.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;

import org.springframework.util.StringUtils;
import org.springframework.utils.SpringContextHolder;

import com.gserver.game.async.SysExecutorManager;
import com.gserver.game.plugin.IPlugin;

/**
 * 用于在IDE环境中停止服务器使用,在命令窗口中输入quit并回车就触发JVM退出逻辑. 在生产环境下不要使用.
 * 
 * 
 * 
 */
public class IDEJVMExit implements IPlugin {
	private volatile boolean start = false;
	private BufferedReader console;

	public IDEJVMExit() {
		console = new BufferedReader(new InputStreamReader(System.in));
	}

	public boolean start() {
		start = true;

		SysExecutorManager bean = SpringContextHolder
				.getBean(SysExecutorManager.class);
		if (bean == null) {
			System.err.println("IDEJVMExit_bean未初始化:" + bean);
		}
		bean.scheduleTask(new Runnable() {
			public void run() {
				shutdownInput();
			}
		}, 1000);
		return true;
	}

	public boolean stop() {
		start = false;
		return true;
	}

	private void shutdownInput() {
		if (!start) {
			return;
		}
		try {
			// 在此处先判断是否有数据,防止调用线程长时间挂起
			if (!console.ready()) {
				return;
			}
			String _line = console.readLine();
			if (!StringUtils.isEmpty(_line)) {
				_line = _line.trim();
			} else {
				System.out.println("cmd...");
				return;
			}
			if (_line.equals("quit")) {
				System.exit(0);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		}
	}

	/**
	 * 内部命令停机处理，如world发来的指令。
	 */
	public void cmdShutdown() {
		console = new BufferedReader(new StringReader("quit"));
	}

	public void check() {
		// TODO Auto-generated method stub

	}

	public void init() {
		// TODO Auto-generated method stub

	}

}
